﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Security;

namespace MvcApplication1
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        MvcApplication1.Models.DataToSearch dts;
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            //routes.MapPageRoute("", "", "~/index.htm");
            routes.MapRoute("", "q/{searchtext}/{page}", new { controller = "Home", action = "Search", searchtext = "", page = 1 });
            routes.MapRoute("Query", "q/{searchtext}", new { controller = "Home", action = "Search",searchtext="" });
            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}", /*/{id}", // URL with parameters*/
                new { controller = "Home", action = "Index" }/*, id = UrlParameter.Optional } // Parameter defaults*/
            );
            

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            //SqlDependency.Start(ConfigurationManager.ConnectionStrings["cj"].ConnectionString);
            string sqlconnstr = ConfigurationManager.ConnectionStrings["cj"].ConnectionString;
            dts = new MvcApplication1.Models.DataToSearch(sqlconnstr);
            dts.Init();
            HttpContext.Current.Application.Add("datatosearch", dts);
        }
        protected void Application_End()
        {
            //SqlDependency.Stop(ConfigurationManager.ConnectionStrings["cj"].ConnectionString);
        }
        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            if (HttpContext.Current.Request["RequireUploadifySessionSync"] != null)
                UploadifySessionSync();
        }

        /// <summary>
        /// Uploadify uses a Flash object to upload files. This method retrieves and hydrates Auth and Session objects when the Uploadify Flash is calling.
        /// </summary>
        /// <remarks>
        ///     Kudos: http://geekswithblogs.net/apopovsky/archive/2009/05/06/working-around-flash-cookie-bug-in-asp.net-mvc.aspx
        ///     More kudos: http://stackoverflow.com/questions/1729179/uploadify-session-and-authentication-with-asp-net-mvc
        /// </remarks>
        protected void UploadifySessionSync()
        {
            try
            {
                string session_param_name = "SessionId";
                string session_cookie_name = "ASP.NET_SessionId";

                if (HttpContext.Current.Request[session_param_name] != null)
                    UploadifyUpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
            }
            catch { }

            try
            {
                string auth_param_name = "SecurityToken";
                string auth_cookie_name = FormsAuthentication.FormsCookieName;

                if (HttpContext.Current.Request[auth_param_name] != null)
                    UploadifyUpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]);
            }
            catch { }
        }

        private void UploadifyUpdateCookie(string cookie_name, string cookie_value)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
            if (cookie == null)
                cookie = new HttpCookie(cookie_name);
            cookie.Value = cookie_value;
            HttpContext.Current.Request.Cookies.Set(cookie);
        }
    }
}